package com.ruoyi.video.server.push;

import com.ruoyi.video.domain.VideoCamera;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 向应用推送设备信息和上下线状态
 */
@Aspect
@Component
@Slf4j
public class PushAspect {
    @Autowired
    private PushServer pushServer;

    @After("@annotation(pushData)")
    public void doAfter(JoinPoint point, PushData pushData) throws Throwable
    {
        if(!PushServer.running) {
            log.warn("级联插件暂停，不需要向上推送数据");
            return;
        }

        if(!pushData.name().equalsIgnoreCase("video_camera")){
            log.error("暂不支持的消息: {} - {}", pushData.name(), pushData.action());
            return;
        }
        new Thread(()->{
            Object p = point.getArgs()[0];
            if(pushData.action().equalsIgnoreCase(PushData.ACTION_ADD)
                    ||pushData.action().equalsIgnoreCase(PushData.ACTION_UPDATE)){
                VideoCamera videoCamera = (VideoCamera)p;
                pushServer.push(pushData.action(), ((VideoCamera) p).getId(), videoCamera);
            }else if(pushData.action().equalsIgnoreCase(PushData.ACTION_DELETE)){
                if(p.getClass().isArray()){
                    for(Long id: (Long[])p){
                        pushServer.push(PushMessage.DEVICE_REMOVE, id, null);
                    }
                }else{
                    pushServer.push(PushMessage.DEVICE_REMOVE, (Long)p, null);
                }
            }else{
                log.error("暂不支持的消息: {} - {}", pushData.name(), pushData.action());
            }
        }).start();

    }

}
